﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.IO;
using Microsoft.Win32;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;

namespace UDPServer
{
    public class PrintBYCtrl
    {

        #region 系统函数


        const int WM_MOUSEACTIVATE = 0x21;
        const int WM_MOUSEHOVER = 0x2A1;
        const int WM_MOUSELEAVE = 0x2A3;
        //const int WM_MOUSEMOVE = 0x200;

        const int BM_SETCHECK = 0x00F1;
        const int BM_CLICK = 0x00F5;
        const int WM_ACTIVE = 0x0006;
        const int WA_ACTIVE = 0x0001;
        const int WM_SETFOCUS = 0x0007;
        const int WM_LBUTTONDBLCLK = 0x0203;
        const int MK_LBUTTON = 0x0001;
        const int WM_MOUSEMOVE = 0x200;
        const int WM_LBUTTONDOWN = 0x201;
        const int WM_LBUTTONUP = 0x202;
        const int WM_SETTEXT = 0x000C;

        const int WM_KEYDOWN = 0x0100;
        const int WM_KEYUP = 0x0101;
        const int WM_CHAR = 0x0102;

        const int WM_SYSKEYDOWN = 0x0104;
        const int WM_SYSKEYUP = 0x0105;
        const int WM_SYSCHAR = 0x0106;

        const int LVM_FIRST = 0x1000;
        const int HDM_FIRST = 0x1200;
        const int LVM_GETITEMCOUNT = LVM_FIRST + 4;

        const int VK_F1 = 0x0070;
        const int VK_F2 = 0x0071;
        const int VK_F3 = 0x0072;

        const int WM_GETTEXT = 0x000D;
        const int WM_GETTEXTLENGTH = 0x000E;
        const int WM_CLOSE = 0x10;

        public struct SERVICE_STATUS
        {
            public int dwServiceType;
            public int dwCurrentState;
            public int dwControlsAccepted;
            public int dwWin32ExitCode;
            public int dwServiceSpecificExitCode;
            public int dwCheckPoint;
            public int dwWaitHint;
        }
        public struct Rect
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        //函数指针类型
        public delegate bool EnumChildWindowsProc(IntPtr hwnd, int lParam);

        //函数指针类型
        public delegate bool EnumWindowsProc(IntPtr hWnd, int lParam);

        [DllImport("user32.dll")]
        public static extern int GetWindowTextLength(IntPtr hWnd);


        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder lpText, int nCount);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int GetWindowRect(IntPtr hWnd, out Rect lpRect);

        [DllImport("user32.dll")]
        static extern int EnumWindows(EnumWindowsProc hWnd, IntPtr lParam);


        [DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hwnd);

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("user32.dll")]
        public static extern int PostMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
        [DllImport("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
        [DllImport("User32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, StringBuilder lParam);

        // 给窗口发送消息
        [DllImport("user32.dll", EntryPoint = "SendMessageA")]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        // 给窗口发送消息，事件返回的数据通过Byte[]数组获得
        [DllImport("user32.dll", EntryPoint = "SendMessageA")]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, Byte[] lParam);


        [DllImport("user32.dll")]
        public static extern int GetClassName(IntPtr hwnd, StringBuilder lpClassName, int nMaxCount);
        [DllImport("user32.dll")]
        public static extern int EnumChildWindows(IntPtr hWndParent, EnumChildWindowsProc lpEnumFunc, int lParam);

        [DllImport("user32.dll")]
        public static extern bool IsWindowVisible(IntPtr hWnd);

        [DllImport("user32.dll")]
        public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);

        [DllImport("kernel32.dll", EntryPoint = "CreateFile")]
        public static extern int CreateFile(
            string lpFileName,      //   file   name   
            int dwDesiredAccess,    //   access   mode   
            int dwShareMode,         //   share   mode
            int lpSecurityAttributes,   //   SD   
            int dwCreationDisposition,    //   how   to   create
            int dwFlagsAndAttributes,     //   file   attributes   
            int hTemplateFile              //   handle   to   template   file   
            );

        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(
            int hObject       //   handle   to   object   
            );
        [DllImport("kernel32.dll")]
        private static extern uint GetLastError();

        [DllImport("advapi32.dll")]
        public static extern IntPtr OpenSCManager(string lpMachineName, string lpSCDB, int scParameter);
        [DllImport("Advapi32.dll")]
        public static extern IntPtr CreateService(IntPtr SC_HANDLE, string lpSvcName, string lpDisplayName,
        int dwDesiredAccess, int dwServiceType, int dwStartType, int dwErrorControl, string lpPathName,
        string lpLoadOrderGroup, int lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword);
        [DllImport("advapi32.dll")]
        public static extern void CloseServiceHandle(IntPtr SCHANDLE);
        [DllImport("advapi32.dll")]
        public static extern int StartService(IntPtr SVHANDLE, int dwNumServiceArgs, string lpServiceArgVectors);
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern IntPtr OpenService(IntPtr SCHANDLE, string lpSvcName, int dwNumServiceArgs);
        [DllImport("advapi32.dll")]
        public static extern int DeleteService(IntPtr SVHANDLE);
        [DllImport("advapi32.dll")]
        public static extern int QueryServiceStatus(IntPtr SVHANDLE, [MarshalAs(UnmanagedType.Struct)] ref SERVICE_STATUS status);


        string m_strFuzzyTitle;
        IntPtr m_hWndFuzzy;
        public string strControlsName = "";
        //根据标题模糊查找窗口
        private IntPtr FuzzySearchWindowsByTitle(string strTitle)
        {
            m_strFuzzyTitle = "";
            m_hWndFuzzy = IntPtr.Zero;

            m_strFuzzyTitle = strTitle;
            //枚举所有窗口，并进行模糊查找
            EnumWindows(enumWindowsCallBack, IntPtr.Zero);

            //如果m_hWndFuzzy不为空，说明已经查找到窗体，返回 true 
            if (m_hWndFuzzy != IntPtr.Zero)
                return m_hWndFuzzy;


            return IntPtr.Zero;

        }
        List<string> classname = new List<string>();
        //枚举窗口的回调函数
        private bool enumWindowsCallBack(IntPtr hWnd, int lParam)
        {
            //分配空间
            var sb = new StringBuilder(50);
            //获取窗口标题
            GetWindowText(hWnd, sb, sb.Capacity);

            //注意某些窗口没有标题
            //比较窗口标题，是否包含我们指定的字符串
            if (sb.ToString() == m_strFuzzyTitle)
            {
                //如果窗口标题包含该字符串，则给句柄赋值
                m_hWndFuzzy = hWnd;
                //返回FAlse，说明已经找到该窗口，停止查找
                return false;
            }

            //回调函数有返回值
            return true;
        }

        int GetListViewCount(IntPtr wnd)
        {
            return SendMessage(wnd, LVM_GETITEMCOUNT, IntPtr.Zero, IntPtr.Zero);
        }
        #endregion


        static PrintBYCtrl myself = null;

        //系统参数参数管理类
        SystemParam sysParam = SystemParam.Create();
        IntPtr m_hwnd_markbutton;
        int m_hwndFindIdx = 0;
        int m_hwndFindIdxMin = 0;
        public int iFeedCount = 0;

        public IntPtr m_hwnd_Main;

        public static PrintBYCtrl Create()
        {
            if (myself == null) myself = new PrintBYCtrl();
            return myself;
        }

        private PrintBYCtrl()
        {

        }

        public IntPtr OpenPrintWindow()
        {
            //获取Laser窗口 
            IntPtr hwnd_win = FindPrintWindow();
            //将激光窗口放在最前面　 
            //SetForegroundWindow(hwnd_win); 
            return hwnd_win;
        }

        public IntPtr FindPrintWindow()
        {
            string strTitle = "PrintExp";
            //获取汉森软件窗口 
            IntPtr hwnd_win = IntPtr.Zero;
            hwnd_win = FuzzySearchWindowsByTitle(strTitle);
            //如果窗口没找到，程序也没启动，进行后续的异常处理
            if (hwnd_win == IntPtr.Zero)
            {
                //加入相关的处理代码
                return IntPtr.Zero;
            }
            m_hwnd_Main = hwnd_win;
            return hwnd_win;
        }

        private bool GetTextMessage(IntPtr hwnd_win)
        {
            //找工具栏WindowsForms10.ToolbarWindow32.app.0.141b42a_r12_ad1
            m_hwnd_markbutton = FindWindowEx(hwnd_win, new IntPtr(0), "WindowsForms10.msctls_statusbar32.app.0.141b42a_r12_ad1", "");
            int textLen;
            textLen = SendMessage(m_hwnd_markbutton, WM_GETTEXTLENGTH, 0, 0);
            Byte[] byt = new Byte[textLen];
            SendMessage(m_hwnd_markbutton, WM_GETTEXT, textLen + 1, byt);
            sysParam.StatusInformation = Encoding.Default.GetString(byt);
            return true;
        }

        private bool SendButtonClick(IntPtr hwnd_win)
        {
            m_hwnd_markbutton = FindWindowEx(hwnd_win, new IntPtr(0), "Button", "确定");
            if (m_hwnd_markbutton != IntPtr.Zero)
            {
                //将窗口放在最前面　 
                SetForegroundWindow(m_hwnd_markbutton);
                SendMessage(m_hwnd_markbutton, BM_CLICK, 0, 0);
            }
            //发送“确定”按钮按下事件
            return true;
        }

        private void SendButtonMessage()
        {
            SendMessage(m_hwnd_markbutton, BM_CLICK, 0, 0);
        }

        private void SendButtonDownMessage()
        {
            PostMessage(m_hwnd_markbutton, WM_LBUTTONDOWN, IntPtr.Zero, IntPtr.Zero);
        }
        private void SendButtonUpMessage()
        {
            PostMessage(m_hwnd_markbutton, WM_LBUTTONUP, IntPtr.Zero, IntPtr.Zero);
        }


        private bool SendButtonClick()
        {
            IntPtr hwnd_win = FindPrintWindow();
            if (hwnd_win == IntPtr.Zero) return false;
            SendButtonClick(hwnd_win);
            return true;
        }

        /// <summary>
        /// 发送开始按钮指令
        /// </summary>
        /// <param name="hwnd_win"></param>
        public bool SendStartButton(int minIdx = 0)
        {
            return SendButtonClick(sysParam.iButStart, minIdx);
        }
        public bool SendStopButton(int minIdx = 0)
        {
            return SendButtonClick(sysParam.iButStop, minIdx);
        }
        public bool SendPuseButton(int minIdx = 0)
        {
            return SendButtonClick(sysParam.iButPuse, minIdx);
        }
        public bool SendHomeButton(int minIdx = 0)
        {
            return SendButtonClick(sysParam.iButHome, minIdx);
        }
        public bool SendLeftButton(int minIdx = 0)
        {
            return SendButtonClick(sysParam.iButLeft, minIdx);
        }
        public bool SendRightButton(int minIdx = 0)
        {
            return SendButtonClick(sysParam.iButRight, minIdx);
        }
        public bool SendUpButton(int minIdx = 0)
        {
            return SendButtonClick(sysParam.iButUp, minIdx);
        }
        public bool SendDownButton(int minIdx = 0)
        {
            return SendButtonClick(sysParam.iButDown, minIdx);
        }

        public bool SendGetStatus()
        {
            //return SendDialogButton(3);
            return false;
        }

        public bool SendButtonClick_OK()
        {
            return SendButtonClick();
        }

        private bool SendButtonClick(int x, int minIdx = 0)
        {
            IntPtr hwnd_win = FindPrintWindow();
            if (hwnd_win == IntPtr.Zero) return false;
            SendButtonClick(hwnd_win, x, minIdx);
            return true;
        }

        /// <summary>
        /// 发送按键指令
        /// </summary>
        /// <param name="hwnd_win"></param>
        public bool SendButtonClick(IntPtr hwnd_win, int x, int minIdx = 0)
        {
            m_hwndFindIdx = 0;
            m_hwndFindIdxMin = minIdx;
            EnumChildWindowsProc n_EunmWindows = new EnumChildWindowsProc(myCallBackMark);

            //获取窗体上所有控件的句柄
            EnumChildWindows(hwnd_win, n_EunmWindows, 0);
            if (m_hwnd_markbutton == IntPtr.Zero)
                return false;

            //发送按钮按下事件
            if (minIdx == 0) SendButtonMessage();
            if (minIdx == 1) SendButtonDownMessage();
            if (minIdx == 2) SendButtonUpMessage();

            return true;
        }

        public bool myCallBackMark(IntPtr hwnd, int lParam)
        {
            StringBuilder strbu = new StringBuilder(1000);
            GetClassName(hwnd, strbu, 255);
            string strtitle = strbu.ToString();

            if (strtitle.StartsWith("#32770"))
            {
                m_hwnd_markbutton = FindWindowEx(hwnd, new IntPtr(0), "Button", strControlsName);
                if (m_hwnd_markbutton == IntPtr.Zero)
                    return true;
                else
                    return false;
            }
            return true;
        }
    }
}


